import request from '@/router/axios'
import store from '@/store'

/***
 * 通用的抽象类，继承此类的用于与后台交互的js，不用再自己写重复的通用方法
 */
class crudCommonController {
  constructor(param) {
    this.moduleName = param.moduleName;
    this.entityName = param.entityName;
    this.baseUrl = "/" + this.moduleName + '/' + this.entityName
  }

  /**
   * @param param
   * @returns {AxiosPromise}
   */
  doRequest(param) {
    return request(param)
  }

  helloWorld() {
    return this.baseUrl
  }

  fetchPage(query) {
    return this.doRequest({
      url: this.baseUrl + '/page',
      method: 'get',
      params: query
    })
  }

  addObj(obj) {
    return this.doRequest({
      url: this.baseUrl,
      method: 'post',
      data: obj
    })
  }

  getObj(id) {
    return this.doRequest({
      url: this.baseUrl + '/' + id,
      method: 'get'
    })
  }

  putObj(obj) {
    return this.doRequest({
      url: this.baseUrl,
      method: 'put',
      data: obj
    })
  }

  delObj(id) {
    return this.doRequest({
      url: this.baseUrl + '/' + id,
      method: 'delete'
    })
  }

  /**
   * 批量删除
   * @param idsStr 用逗号分隔的id字符串
   * @returns {AxiosPromise}
   */
  deleteBatch(idsStr) {
    return this.doRequest({
      url: this.baseUrl + '/deleteBatch',
      method: 'delete',
      params: {ids: idsStr}
    })
  }

  returnList(entity, orderByColumn, orderByDesc) {
    return this.doRequest({
      url: this.baseUrl + '/returnList',
      method: 'post',
      data: entity,
      params: {
        orderByColumn: orderByColumn, orderByDesc: orderByDesc
      }
    })
  }

  download(method, param) {
    return this.doRequest({
      url: this.baseUrl + '/' + method,
      method: 'post',
      responseType: 'blob',
      params: param
    })
  }

  exportExcel(url, paramsObj, postObj) {
    function callBackExcel(res) {
      function blobToDataURL(b, callback) {
        let a = new FileReader()
        a.onload = function (e) {
          callback(e.target.result)
        }
        a.readAsDataURL(b)
      }

      //console.log(res)
      const {data, headers} = res
      // let blob = new Blob([data], {type: headers['content-type']})
      const blob = new Blob([data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})
      // const fileName = res.getResponseHeader('Content-Disposition').split(';')[1].split('filename=')[1];
      let fileName = decodeURI(headers['content-disposition'])
      fileName = fileName.split('filename=')[1]
      if (blob.size === 0) {
        this.$alert('下载文件为空')
        return false
      }
      blobToDataURL(blob, function (dataUrl) {
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        document.body.appendChild(link)
        link.click()
        window.setTimeout(function () {
          URL.revokeObjectURL(link.href)//不用在内存中继续保留对这个文件的引用
          document.body.removeChild(link)
        }, 0)
      })
    }

    let _this = this

    return new Promise(function (resolve, reject) {
      _this.doRequest({
        url: url,
        method: 'post',
        responseType: 'blob',
        params: paramsObj,
        data: postObj,
        headers: {
          Authorization: 'Bearer ' + store.getters.token
        }
      }).then(res => { // 处理返回的文件流
        callBackExcel(res)
        resolve(res)
      }).catch(
        res => { // 处理返回的文件流
          reject(res)
        }
      )
    })
  }

  exportExcelForVue($vue, method, paramsObj, postObj) {
    let notify = $vue.$notify.success({
      title: '准备从后台获取数据',
      message: '<i class="el-icon-loading"></i>',
      dangerouslyUseHTMLString: true,
      showClose: false,//不允许用户关闭
      position: 'bottom-right',
      duration: 0//不自动关闭
    })
    this.exportExcel(this.baseUrl + '/' + method, paramsObj, postObj)
      .then(res => {
        notify.close()
        $vue.$message.success('获取数据成功，开始从后台下载文件')
      }).catch(res => {
      notify.close()
      $vue.$message.error('下载失败' + res)
    })
  }
}

export default crudCommonController
